package com.shanzmoo.base.util;

import com.alibaba.fastjson.JSON;
import com.shanzmoo.base.bean.SResponse;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应工具类
 *
 * @author: Gzhao 2020/11/6
 */
public class SResponseUtils {

    private SResponseUtils() {
    }

    /**
     * 返回json响应
     *
     * @param response
     * @param sResponse
     * @throws IOException
     */
    public static void outputJson(HttpServletResponse response, SResponse sResponse) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        PrintWriter printWriter = response.getWriter();
        try {
            printWriter.print(JSON.toJSONString(sResponse));
            printWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            printWriter.close();
        }
    }

    /**
     * 返回 String 响应
     *
     * @param response
     * @param resStr
     */
    public static void outputStr(HttpServletResponse response, String resStr) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(resStr.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
